#include "NeoComboBox.h"
#include "NeoScrollBar.h"
#include "private/NeoComboBoxPrivate.h"
#include "style/NeoComboBoxStyle.h"
#include <QLayout>
#include <QListView>

NeoComboBox::NeoComboBox(QWidget *parent)
    : QComboBox(parent), d_ptr(new NeoComboBoxPrivate())
{
    NEO_PUBLIC_POINT(NeoComboBox)
    d->q_ptr = this;
    this->setMaxVisibleItems(5);
    this->setStyle(new NeoComboBoxStyle(this->style()));

    this->setView(new QListView(this));
    this->view()->setSelectionMode(QAbstractItemView::NoSelection);
    this->view()->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    this->view()->setFrameShape(QFrame::NoFrame);
    this->view()->setAutoScroll(false);
    this->view()->setStyle(this->style());
    NeoScrollBar *scrollBar = new NeoScrollBar(this->view(), Qt::Vertical);

    this->findChild<QFrame *>()->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);
    this->findChild<QFrame *>()->setAttribute(Qt::WA_TranslucentBackground);
    this->findChild<QFrame *>()->setStyle(this->style());

    connect(d->pFixedSizeAnimation, &QPropertyAnimation::valueChanged, this, [=](const QVariant &value)
            { this->findChild<QFrame *>()->setFixedHeight(value.toUInt()); });
    connect(d->pFixedSizeAnimation, &QPropertyAnimation::finished, this, [=]()
            {
                NEO_PUBLIC_POINT(NeoComboBox);
                if(d->pFixedSizeAnimation->direction() == QAbstractAnimation::Forward)
                {
                    d->pIsShowView = true;
                }
                else if (d->pFixedSizeAnimation->direction() == QAbstractAnimation::Backward)
                {
                    d->pIsShowView = false;
                    QComboBox::hidePopup();
                } });
}

NeoComboBox::~NeoComboBox() = default;

void NeoComboBox::showPopup()
{
    NEO_PUBLIC_POINT(NeoComboBox)
    if (!d->pIsShowView)
    {
        bool oldAnimationEffects = qApp->isEffectEnabled(Qt::UI_AnimateCombo);
        qApp->setEffectEnabled(Qt::UI_AnimateCombo, false);
        QComboBox::showPopup();
        qApp->setEffectEnabled(Qt::UI_AnimateCombo, oldAnimationEffects);
        d->startShowPopupAnimation();
    }
}

void NeoComboBox::hidePopup()
{
    NEO_PUBLIC_POINT(NeoComboBox)
    if (d->pIsShowView)
    {
        d->startHidePopupAnimation();
    }
}